package cn.appsys.controller.backend;

import cn.appsys.pojo.BackendUser;
import cn.appsys.service.backend.BackendUserService;
import cn.appsys.tools.Constants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 登录的控制层
 * @author jie
 * @date 2019/3/6 -21:30
 */
@Controller
@RequestMapping("/manager")
public class UserLoginController {

    /**
     * 用户相关的业务类
     */
    @Resource
    private BackendUserService backendUserService;

    /**
     * 跳转到后台管理系统
     * @return 后台管理系统页面
     */
    @RequestMapping(value = "/login")
    public String login() {
        return "backendlogin";
    }

    /**
     * 进入后台管理前的登录验证
     * @param userCode 用户名
     * @param userPassword 密码
     * @param request HttpServletRequest
     * @param session HttpSession
     * @return  成功返回后台主页面
     */
    @RequestMapping(value = "/dologin", method = RequestMethod.POST)
    public String doLogin(@RequestParam String userCode, @RequestParam String userPassword, HttpServletRequest request, HttpSession session) {
        //调用service方法，进行用户匹配
        BackendUser user;
        user = backendUserService.login(userCode, userPassword);
        //登录成功
        if (null != user) {
            //放入session
            session.setAttribute(Constants.USER_SESSION, user);
            //页面跳转（main.jsp）
            return "redirect:/manager/backend/main";
        } else {
            //页面跳转（login.jsp）带出提示信息--转发
            request.setAttribute("error", "用户名或密码不正确");
            return "backendlogin";
        }
    }

    /**
     * 用于主页面的跳转
     * @param session HttpSession
     * @return 页面跳转
     */
    @RequestMapping(value="/backend/main")
    public String main(HttpSession session){
        if(session.getAttribute(Constants.USER_SESSION) == null){
            return "redirect:/manager/login";
        }
        return "backend/main";
    }

    /**
     * 用户登出操作
     * @param session HttpSession
     * @return 后台管理系统页面
     */
    @RequestMapping(value="/logout")
    public String logout(HttpSession session){
        //清除session
        session.removeAttribute(Constants.USER_SESSION);
        return "backendlogin";
    }
}
